package otelhertz

import (
	"context"
	"fmt"
	"github.com/cloudwego/hertz/pkg/app"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/codes"
	oteltrace "go.opentelemetry.io/otel/trace"
)

const (
	tracerKey = "otel-go-contrib-tracer"
	// ScopeName is the instrumentation scope name.
	ScopeName = " gitcode.com/sznc/uptrace-opentelemetry/uptrace-opentelemetry/otelhertz"
)

func HTML(c context.Context, ctx *app.RequestContext, code int, name string, obj interface{}) {
	var tracer oteltrace.Tracer
	tracerInterface, ok := ctx.Get(tracerKey)
	if ok {
		tracer, ok = tracerInterface.(oteltrace.Tracer)
	}
	if !ok {
		tracer = otel.GetTracerProvider().Tracer(
			ScopeName,
			oteltrace.WithInstrumentationVersion(Version()),
		)
	}
	opt := oteltrace.WithAttributes(attribute.String("go.template", name))
	_, span := tracer.Start(c, "hertz.renderer.html", opt)
	defer func() {
		if r := recover(); r != nil {
			err := fmt.Errorf("error rendering template:%s: %s", name, r)
			span.RecordError(err)
			span.SetStatus(codes.Error, "template failure")
			span.End()
			panic(r)
		}
		span.End()
	}()
	ctx.HTML(code, name, obj)
}
